package org.cos.verification.verifier;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

import org.shellex.javame.utility.Screen;

public class RuleViewerScreen extends Screen {
	public List screen; 
	
	private Command editRuleCmd;

	private Command back2mainCmd;
	
	static RuleViewerScreen instance;
	
	public static RuleViewerScreen getInstance()
	{
		if(instance == null)
			instance = new RuleViewerScreen();
		return instance;
	}

	public void crackCommand(MIDlet midlet, Command cmd, Displayable screen) {
		if (cmd == editRuleCmd) {
//			Alert alert = new Alert("Select");
//			alert.setType(AlertType.INFO);
//			alert.setString(String.valueOf(idx));
//			Display.getDisplay(midlet).setCurrent(alert);
			int idx = this.screen.getSelectedIndex();
			SharePool.getInstance().currentRuleName = this.screen.getString(idx);
			RuleEditorScreen.getInstance().display(midlet);
		} else if (cmd == back2mainCmd){
			MainScreen.getInstance().display(midlet);
		} 
	}

	public Screen initCommand() {
		back2mainCmd = new Command("返回主页", Command.EXIT, 1);
		editRuleCmd = new Command("编辑规则", Command.ITEM, 1);
		screen.addCommand(back2mainCmd);
		screen.addCommand(editRuleCmd);
		return this;
	}

	public Screen initUI(MIDlet midlet) {
		screen = new List("规则编辑器", List.IMPLICIT);
		screen.append("Rule1", null);
		return this;
	}
	
	public void setCommandListener(CommandListener cmdl) {
		screen.setCommandListener(cmdl);
	}
	
	private void reloadRuleDB() {
		Vector rules = RuleManager.getInstance().getAllRule();
		screen.deleteAll();
		
		for (Enumeration enumobj = rules.elements(); enumobj.hasMoreElements();) {
			Rule rule = (Rule)enumobj.nextElement();
			screen.append(rule.name, null);
		}
		return;
	}
	
	public void display(MIDlet midlet) {
		reloadRuleDB();
		Display.getDisplay(midlet).setCurrent(screen);
	}
}
